<template>
  <div class="app-container">
    <!-- 搜索和重置 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="4.25rem">
      <el-form-item label="菜品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品分类" prop="classify">
        <el-select v-model="queryParams.classifyId" placeholder="请选择菜品分类" clearable>
          <el-option
            v-for="dict in classify"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择菜品状态" clearable>
          <el-option label="已上架" value="0" />
          <el-option label="已下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐" prop="status">
        <el-select v-model="queryParams.isRecommend" placeholder="是否推荐" clearable>
          <el-option label="已推荐" value="0" />
          <el-option label="未推荐" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增和修改 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="!single"
          @click="handleUpdate"
          v-hasPermi="['system:post:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="!multiple && !single"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格内容 -->
    <el-table v-loading="loading" :data="menuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="菜品名称" align="center" prop="name" />
      <el-table-column label="菜品分类" align="center">
        <template slot-scope="scope">
          {{ getClassifyName(scope.row.classifyId) }}
        </template>
      </el-table-column>
      <el-table-column label="菜品图片" align="center" prop="image" >
        <template slot-scope="scope">
          <el-image
            :src="scope.row.image"
            :value="scope.row.image"
            :preview-src-list="[scope.row.image]"
            style="width: 6.25rem; height: 3.125rem">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="菜品售价" align="center" prop="sprice" />
      <el-table-column label="菜品原价" align="center" prop="oprice" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '1' ? 'danger' : ''"
            :key="scope.row.status"
            :value="scope.row.status"
            @click="updateStatus(scope.row)">
            {{scope.row.status === '0' ? '已上架' : '已下架'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template slot-scope="scope">
          <el-tag
            :key="scope.row.isRecommend"
            :value="scope.row.isRecommend"
            :type="scope.row.isRecommend === '1' ? 'danger' : ''"
            @click="updateRecommend(scope.row)">
            {{scope.row.isRecommend === '0' ? '已推荐' : '未推荐'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editSpec(scope.row)"
          >编辑规格</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      :title="specFormList.length > 0 ? `${specFormList[0].tasteName}的商品规格` : ''" width="400"
      :visible.sync="showSpecDrawer">
      <el-button
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="handleAddSpec"
        style="margin: 15px"
      >新增菜品规格</el-button>
      <el-table
        :data="specFormList"
        stripe
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="size"
          label="规格值">
        </el-table-column>
        <el-table-column
          prop="price"
          label="规格价格">
        </el-table-column>
        <el-table-column label="操作"  >
          <template slot-scope="scope">

            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateSpec(scope.row)"
              v-hasPermi="['system:post:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteSpec(scope.row)"
              v-hasPermi="['system:post:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 修改规格弹框 -->
    <el-dialog
      title="修改规格"
      :visible.sync="specdialogVisible"
      width="20%">
      <el-form ref="form" :model="specForm" label-width="80px">
          <el-form-item label="规格值"><el-input v-model="specForm.size"></el-input></el-form-item>
          <el-form-item label="规格价格"><el-input v-model="specForm.price"></el-input></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="specdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="specSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="31.25rem" append-to-body :destroy-on-close="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="5rem">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品分类" prop="classifyId">
          <el-select v-model="form.classifyId" placeholder="请选择菜品分类" clearable>
            <el-option
              v-for="dict in classify"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片" prop="image">
          <el-upload
            action="http://192.168.8.47:10100/system/oss/upload"
            list-type="picture-card"
            :headers="uploadHeaders"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="菜品售价" prop="sprice">
          <el-input v-model="form.sprice" placeholder="请输入菜品售价" />
        </el-form-item>
        <el-form-item label="菜品原价" prop="oprice">
          <el-input v-model="form.oprice" placeholder="请输入菜品原价" />
        </el-form-item>
        <el-form-item label="菜品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">不上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio-group v-model="form.isRecommend">
            <el-radio label="0">推荐</el-radio>
            <el-radio label="1">不推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜品说明" prop="foodExplain">
          <el-input v-model="form.foodExplain" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFood, listClassify, addFood, updateFood, delFood, addFoodSpec, delFoodSpec, getFoodIdSpec, editFoodIdSpec } from "@/api/scancode/food";
import { getToken } from '@/utils/auth'
import { formatDate } from '@/utils'
import { add } from "zrender/lib/core/vector";

const checkPrice = (rule, value, callback) => {
  if (value < 0) {
    callback(new Error('价格不能为负数'));
  } else {
    callback();
  }
};

export default {
  name: "Post",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      //上下架
      statusOption:[
        {
          id: 1, // for循环唯一key值
          label: '已上架', // 页面展示文本
          value: '0' // 值
        },
        {
          id: 2,
          label: '已下架',
          value: '1'
        }
      ],
      //是否推荐
      // upDwon:[
      //   {
      //     value: '选项1',
      //     label: '不推荐'
      //   },
      //   {
      //     value: '选项2',
      //     label: '推荐'
      //   }
      // ],
      //菜品分类
      classify:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: false,
      // 非多个禁用
      multiple: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜单表格数据
      menuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        classifyId: undefined,
        status: undefined,
        isRecommend:undefined
      },
      // 表单参数
      form: {
        name:'',
        classifyId:'',
        image:'',
        sprice:'',
        oprice:'',
        isRecommend:'',
        foodExplain: '',
        status:'',
        createTime:''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "菜品名称不能为空", trigger: "blur" }
        ],
        classifyId: [
          { required: true, message: "菜品分类不能为空", trigger: "blur" }
        ],
        sprice: [
          { required: true, message: "菜品售价不能为空", trigger: "blur" },
          { validator: checkPrice, message: "价格不能为负数", trigger: "blur" }
        ],
        oprice: [
          { required: true, message: "菜品原价不能为空", trigger: "blur" },
          { validator: checkPrice, message: "价格不能为负数", trigger: "blur" }
        ]
      },
      classify:[],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      selection: [],
      uploadHeaders: { Authorization: getToken() },
      specdialogVisible: false,
      specId: '',
      specFormList:[],
      showSpecDrawer: false,
      specForm:{}
    };
  },
  created() {
    this.getList();
    // 分类接口
    listClassify().then( res => {
      this.classify  = res.rows
    })
  },
  methods: {
    //清空
    empty(){
      this.form = {
        name:'',
        classifyId:'',
        image:'',
        sprice:'',
        oprice:'',
        isRecommend:'',
        foodExplain: '',
        status:''
      }
    },
    handleSuccess(res, file) {
      this.form.image = res.data.url
    },
    handleRemove(file, fileList) {
        console.log(file, fileList, 'file, fileLis');
    },
    handlePictureCardPreview(file) {
      console.log(file, 'file')
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
        console.log(file);
      },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listFood(this.queryParams).then(response => {
        this.menuList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      // 对整个表单进行  重置   ，将所有字段值   重置为初始值   并移除校验结果
      this.$refs.form.resetFields();
      console.log(this.form)
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.single = selection.length === 1;
      this.multiple = selection.length > 1;
      this.selection = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "添加菜品";
      this.empty();
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = { ...row };
      this.title = "修改菜品";
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateFood(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.getList();
            });
          } else {
            this.form.createTime = new Date().getTime()
            addFood(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              let addFoodSpecData = {
                foodId: response.msg,
                size: "一人份",
                price: this.form.sprice,
                tasteName: this.form.name
              }
              addFoodSpec(addFoodSpecData).then( res => {
                this.specId = res.msg
              })
              this.cancel();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let params = [], names = [];
      if (row.id) {
        params = row.id;
        names = row.name;
      } else if(this.single) {
        params = this.selection[0].id;
        names = this.selection[0].name;
      } else if(this.multiple) {
        this.selection.forEach( item => {
          params.push(item.id);
          names.push(` ${item.name} `);
        })
      }
      this.$confirm(`确认删除${ names }这${ typeof names != 'string' ? names.length : '' }个菜品嘛？`)
      .then(_ => {
        delFood(params).then( res => {
          console.log(this.specId, 'delspec')
          delFoodSpec(this.specId).then( respon => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          })
        })
      })
      .catch(_ => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scancode/food', {
        ...this.queryParams
      }, `get_${new Date().getTime()}.xlsx`)
    },
    // 获取分类名称
    getClassifyName(id) {
      for (let i=0; i<this.classify.length; i++) {
        if (this.classify[i].id === id) {
          return this.classify[i].name
        }
      }
    },
    updateStatus(row) {
      this.form = { ...row };
      this.form.status = this.form.status === '0' ? '1' : '0';
      updateFood(this.form).then( response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    updateRecommend(row){
      this.form = { ...row };
      this.form.isRecommend = this.form.isRecommend === '0' ? '1' : '0';
      updateFood(this.form).then( response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    // 取消编辑
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    //编辑规格
    editSpec(row){
      getFoodIdSpec(row.id).then( res => {
        this.specFormList = res.rows
        this.showSpecDrawer = true
      })
    },
    // 修改
    handleUpdateSpec(data) {
      this.specForm = { ...data }
      this.specdialogVisible = true
    },
    // 新增
    handleAddSpec(){
      this.specForm.foodId = this.specFormList[0].foodId
      this.specForm.tasteName = this.specFormList[0].tasteName
      this.specdialogVisible = true
    },
    // 删除
    handleDeleteSpec(data) {
      this.specForm = { ...data }
      this.$confirm(`确认删除${ this.specForm.tasteName }这个菜品的规格吗？`)
      .then(_ => {
        delFoodSpec(data.id).then( res => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
      })
      .catch(_ => {});
    },
    //确认修改规格
    specSubmit(){
      if(this.specForm.id){
        editFoodIdSpec(this.specForm).then( res =>{
          this.$modal.msgSuccess("修改成功!");
          this.getList();
        })
      }else{
        addFoodSpec(this.specForm).then( res => {
          this.$modal.msgSuccess("新增菜品规格成功!");
          this.getList();
        })
      }
      this.specdialogVisible = false
    }
  }
};
</script>

<style lang="scss" scoped>
  .el-tag {
    cursor: pointer;
  }
</style>
